<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>通讯录</title>
    <style>
        h1{ color:red;}
        input{
            padding: 8px;
            border-radius: 6px;
            margin: 5px 0;
        }
        .errMsg{
            color: red;
            font-weight: bold;
        }
    </style>

</head>
<body><?php
$db=new PDO('mysql:host=localhost;dbname=db','root','12qwas');
if($_POST){ //判断是否提交有数据
    try {
        session_start(); //启用session功能
        $xh = $_POST['xh'];
        $pwd = $_POST['pwd'];
        $ps = $db->prepare("select * from students where xh=? and pwd=?");
        $ps->execute(array($xh, $pwd));
        $user=$ps->fetch(PDO::FETCH_ASSOC);
        if($user){ //用户登录成功，把登录成功的用户信息(数组)保存到session中
            $_SESSION['user']=$user;
            header("location: index.php");
            return;
        }else{ //登录失败，则删除 Session中保存的信息
            unset($_SESSION['user']);
            throw new Exception('用户名或口令错误~');
        }


    }catch(Throwable $e){
        $errMsg = $e->getMessage(); //获取错误信息
    }
}
?>
<h1>用户登录</h1>
<form method="post">
    学号：<input type="text" name="xh" value="<?=htmlentities($xh??'')?>" /><br>
    密码：<input type="password" name="pwd" value="<?=htmlentities($pwd??'')?>" /><br>
    <div class="errMsg"><?=htmlentities($errMsg??'')?></div>
    <input type="submit" value=" 用户登录 " /> <input type="submit" value=" 注册用户 " /><br>
</form>

</body>
</html>